package org.itzheng.itplayer.player

import android.app.Application
import android.content.res.Configuration
import android.media.MediaPlayer
import android.util.Log
import android.view.Surface
import android.view.View
import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * Title:<br>
 * Description: <br>
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-8-6.
 */
class VideoPlayViewModel() : ViewModel() {
    /**
     * 播放器
     */
    val mediaPlayer = MyMediaPlayer()

    private val _loadingBarVisibility = MutableLiveData(View.VISIBLE)

    /**
     * 加载条可见状态，进行缓存的时候需要显示加载
     */
    val loadingBarVisibility: LiveData<Int> = _loadingBarVisibility

    /**
     *控制栏可见状态
     */
    private val _controllerLayoutVisibility = MutableLiveData(View.VISIBLE)

    /**
     * 控制栏可见状态，点击弹出
     */
    val controllerLayoutVisibility: LiveData<Int> = _controllerLayoutVisibility
    private val _bufferingPercent = MutableLiveData(0)

    /**
     * 缓存
     */
    val bufferingPercent: LiveData<Int> = _bufferingPercent

    /**
     * 视频分辨率
     */
    private val _videoResolution = MutableLiveData(Pair(0, 0))

    /**
     * 视频分辨率
     */
    val videoResolution: LiveData<Pair<Int, Int>> = _videoResolution
    private val _totalDuration = MutableLiveData(0)

    /**
     * 总时长
     */
    val totalDuration: LiveData<Int> = _totalDuration

    private val _currentDuration = MutableLiveData(0)

    /**
     * 当前时长
     */
    val currentDuration: LiveData<Int> = _currentDuration

    private val _playStatus = MutableLiveData(PlayStatus.notReady)

    /**
     * 播放状态
     */
    val playStatus: LiveData<PlayStatus> = _playStatus
    var tPath = ""

    /**
     * 设置播放路径
     */
    fun setMediaPath(path: String) {
        Log.w(TAG, "setMediaPath: " + path);
        if (tPath != path) {
            tPath = path
            if (false) {
                tPath =
                        "http://stream4.iqilu.com/ksd/video/2020/08/03/9a14a19751f9368c5f84df2daba7d195.mp4"
            }
            loadVideo(0, tPath)
        }
    }

    init {
//        val path =
//            "http://stream4.iqilu.com/ksd/video/2020/08/03/9a14a19751f9368c5f84df2daba7d195.mp4"
//        val proxy = getProxy(application)
//        val proxyUrl = proxy.getProxyUrl(path)
//        loadVideo(0, path)
        updateDuration()
    }

    private val TAG = "VideoPlayViewModel"
    private fun loadVideo(seekTime: Int, path: String) {
        Log.w(TAG, "loadVideo: ${path}")
        mediaPlayer.apply {
            reset()
            _loadingBarVisibility.value = View.VISIBLE
            try {
                setDataSource(path)
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }

            //准备完成
            setOnPreparedListener() {
                Log.w(TAG, "setOnPreparedListener: ");
                _loadingBarVisibility.value = View.GONE
                //总时间
                _totalDuration.value = duration
                seekTo(seekTime)
                start()
                _playStatus.value = PlayStatus.playing
            }
            //大小改变
            setOnVideoSizeChangedListener { mp, width, height ->
                _videoResolution.value = Pair(width, height)
            }
            //缓冲大小
            setOnBufferingUpdateListener { mp, percent ->
                _bufferingPercent.value = percent
            }
            //播放完成
            setOnCompletionListener {
                _playStatus.value = PlayStatus.completion
            }
            setLifecycleListener(object : MyMediaPlayer.LifecycleListener {
                var tIsPlaying = false
                override fun onPause() {
                    tIsPlaying = mediaPlayer.isPlaying
                    if (tIsPlaying) {
                        togglePlayStatus()
                    }
                }

                override fun onResume() {
                    if (tIsPlaying && _playStatus.value != PlayStatus.playing) {
                        togglePlayStatus()
                    }
                }
            })
            setOnErrorListener(object : MediaPlayer.OnErrorListener {
                override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
                    Log.w(TAG, "onError: what${what}")
                    return true
                }
            })
            try {
                //准备播放
                prepareAsync()
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 跳到。。
     */
    fun seekTo(msec: Int) {
        viewModelScope.launch(Dispatchers.Main) {
            mediaPlayer.seekTo(msec)
        }
    }

    /**
     * 更新时间
     */
    private fun updateDuration() {
        viewModelScope.launch(Dispatchers.Main) {
            var currentPosition = 0;
            try {
                while (true) {
                    currentPosition = mediaPlayer.currentPosition
                    if (_currentDuration.value != currentPosition) {
                        _currentDuration.value = currentPosition
                    }
                    delay(200)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    override fun onCleared() {
        super.onCleared()
        mediaPlayer.release()
        Log.w(TAG, "onCleared");
    }

    fun updateSize() {
        _videoResolution.value = _videoResolution.value
    }

    /**
     * 切换播放状态
     */
    fun togglePlayStatus() {
        when (_playStatus.value) {
            PlayStatus.pause -> {
                mediaPlayer.start()
                _playStatus.value = PlayStatus.playing
            }
            PlayStatus.playing -> {
                mediaPlayer.pause()
                _playStatus.value = PlayStatus.pause
            }
            PlayStatus.completion -> {
                mediaPlayer.start()
                _playStatus.value = PlayStatus.playing
            }
        }
    }

    fun setSurface(surface: Surface) {
        mediaPlayer.setSurface(surface)
//        mSurfaceHolder!=null 时才有效,setSurface  mSurfaceHolder==null
//        mediaPlayer.setScreenOnWhilePlaying(true)
    }

    private var currentOrientation = 0

    /**设置屏幕方向，如果是横屏，需要在3秒后自动隐藏进度条
     * Configuration.ORIENTATION_LANDSCAPE
     */
    fun setOrientation(orientation: Int) {
        currentOrientation = orientation
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            goneControllerLayout()
        } else {
            job?.cancel()
            _controllerLayoutVisibility.value = View.VISIBLE
        }
    }

    var job: Job? = null
    private fun goneControllerLayout() {
        job?.cancel()
        job = viewModelScope.launch(Dispatchers.Main) {
            delay(2000)
            if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                _controllerLayoutVisibility.value = View.GONE
            }
        }
    }

    /**
     * 显示进度条，如果是横屏，3秒后，需要自动隐藏
     */
    fun showProgressBar() {
        _controllerLayoutVisibility.value = View.VISIBLE
        goneControllerLayout()
    }

    /**
     * 播放状态
     */
    enum class PlayStatus {
        playing, pause, completion, notReady
    }

    class MyMediaPlayer : MediaPlayer(), LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onPause() {
            mListener?.onPause()
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun onResume() {
            mListener?.onResume()
        }

        var mListener: LifecycleListener? = null
        fun setLifecycleListener(listener: LifecycleListener) {
            mListener = listener
        }

        interface LifecycleListener {
            fun onPause()
            fun onResume()
        }
    }
}